package com.breeze.stack;

/**
 * 共享占空间，通过数组实现
 */
public class SqDoubleStack<T> {
    private T[] datas;
    private final int STACK_SIZE = 10;
    private int t1, t2;

    public SqDoubleStack() {
        datas = (T[]) new Object[STACK_SIZE];
        t1 = -1;
        t2 = STACK_SIZE;
    }

    public SqDoubleStack(int size) {
        datas = (T[]) new Object[size];
        t1 = -1;
        t2 = size;
    }

    public T pop(int sn) {
        if (sn == 1) {
            if (t1 == -1) {
                System.out.println("栈为空");
                return null;
            }
            return datas[t1--];
        }
        if (sn == 2) {
            if (t2 == datas.length) {
                System.out.println("栈为空");
                return null;
            }
            return datas[t2++];
        }
        throw new RuntimeException("非法的栈编号");
    }

    public void push(T data, int sn) {
        if (t1 == t2 - 1) {
            System.out.println("栈已满");
            return;
        }
        if (sn == 1) {
            datas[++t1] = data;
            return;
        }
        if (sn == 2) {
            datas[--t2] = data;
            return;
        }
        throw new RuntimeException("非法的栈编号");
    }

    public void show() {
        for (int i = 0; i < datas.length; i++) {
            System.out.println("i:" + i + ",data:" + datas[i]);
        }
    }
}
